package com.aoeai.rg.language.manager

import android.content.Context
import android.content.res.Configuration
import android.os.Build
import androidx.compose.runtime.staticCompositionLocalOf
import com.aoeai.rg.language.data.repository.LanguageRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.util.Locale

object LanguageManager {
    // 来自AppLanguage的状态管理部分
    private val _currentLanguageCode = MutableStateFlow("")
    val currentLanguageCode: StateFlow<String> = _currentLanguageCode.asStateFlow()

    fun init(repository: LanguageRepository, coroutineScope: CoroutineScope) {
        coroutineScope.launch {
            repository.currentLanguageCode.collect { languageCode ->
                _currentLanguageCode.value = languageCode
            }
        }
    }

    // 整合两个updateLanguage方法
    fun updateLanguage(context: Context, languageCode: String) {
        // 更新语言配置(原LanguageUtil功能)
        val locale = Locale(languageCode)
        Locale.setDefault(locale)

        val resources = context.resources
        val configuration = Configuration(resources.configuration)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            configuration.setLocales(android.os.LocaleList(locale))
        } else {
            configuration.setLocale(locale)
        }

        context.createConfigurationContext(configuration)

        // 更新状态流(原AppLanguage功能)
        _currentLanguageCode.value = languageCode
    }

    // 提供指定语言的Context
    val LocalLanguageContext = staticCompositionLocalOf<Context> {
        error("没有提供语言Context")
    }

    fun Context.createLanguageContext(languageCode: String): Context {
        val parts = languageCode.split("-r", "_", ignoreCase = true)
        val locale = if (parts.size == 2) Locale(parts[0], parts[1]) else Locale(languageCode)
        Locale.setDefault(locale)

        val config = Configuration(resources.configuration)
        config.setLocale(locale)
        return createConfigurationContext(config)
    }
}